<template>
  <div class="register-container">
    <div class="register-box">
      <div class="register-title">
        <h3>商品防伪网站</h3>
        <p>用户注册</p>
      </div>
      <el-form :model="registerForm" :rules="registerRules" ref="registerFormRef" class="register-form" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="registerForm.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="registerForm.realName" placeholder="请输入真实姓名"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="registerForm.phone" placeholder="请输入手机号码"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="registerForm.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="registerForm.role" placeholder="请选择角色" style="width: 100%">
            <el-option label="生产商" value="FARMER"></el-option>
            <el-option label="经销商" value="DEALER"></el-option>
<!--            <el-option label="普通用户" value="CUSTOMER"></el-option>-->
          </el-select>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="registerForm.password" type="password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="registerForm.confirmPassword" type="password" placeholder="请再次输入密码"></el-input>
        </el-form-item>
        
        <!-- 种植户附加信息 -->
<!--        <template v-if="registerForm.role === 'FARMER'">-->
<!--          <div class="form-divider">生产商附加信息</div>-->
<!--          <el-form-item label="农场名称" prop="farmName">-->
<!--            <el-input v-model="registerForm.farmName" placeholder="请输入农场名称"></el-input>-->
<!--          </el-form-item>-->
<!--          <el-form-item label="农场地址" prop="farmAddress">-->
<!--            <el-input v-model="registerForm.farmAddress" placeholder="请输入农场地址"></el-input>-->
<!--          </el-form-item>-->
<!--          <el-form-item label="种植面积" prop="farmArea">-->
<!--            <el-input v-model="registerForm.farmArea" placeholder="请输入种植面积（亩）"></el-input>-->
<!--          </el-form-item>-->
<!--        </template>-->
        
        <!-- 经销商附加信息 -->
<!--        <template v-if="registerForm.role === 'DEALER'">-->
<!--          <div class="form-divider">经销商附加信息</div>-->
<!--          <el-form-item label="公司名称" prop="companyName">-->
<!--            <el-input v-model="registerForm.companyName" placeholder="请输入公司名称"></el-input>-->
<!--          </el-form-item>-->
<!--          <el-form-item label="公司地址" prop="companyAddress">-->
<!--            <el-input v-model="registerForm.companyAddress" placeholder="请输入公司地址"></el-input>-->
<!--          </el-form-item>-->
<!--          <el-form-item label="营业执照" prop="businessLicense">-->
<!--            <el-upload-->
<!--              class="upload-area"-->
<!--              action="/api/file/upload"-->
<!--              :show-file-list="false"-->
<!--              :on-success="handleLicenseSuccess"-->
<!--              :before-upload="beforeLicenseUpload">-->
<!--              <img v-if="registerForm.businessLicenseUrl" :src="registerForm.businessLicenseUrl" class="uploaded-image">-->
<!--              <el-icon v-else><Plus /></el-icon>-->
<!--              <div class="upload-text" v-if="!registerForm.businessLicenseUrl">点击上传</div>-->
<!--            </el-upload>-->
<!--            <div class="upload-tip">请上传营业执照扫描件，仅支持JPG、PNG格式，大小不超过2MB</div>-->
<!--          </el-form-item>-->
<!--        </template>-->
        
        <el-form-item class="register-btn">
          <el-button type="primary" @click="register">注册</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
        <div class="login-link">
          <router-link to="/login">已有账号？返回登录</router-link>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import axios from "axios";

const router = useRouter()
const registerFormRef = ref(null)

const registerForm = reactive({
  username: '',
  realName: '',
  phone: '',
  email: '',
  role: '',
  password: '',
  confirmPassword: '',
  // 种植户信息
  farmName: '',
  farmAddress: '',
  farmArea: '',
  // 经销商信息
  companyName: '',
  companyAddress: '',
  businessLicense: '',
  businessLicenseUrl: ''
})

// 自定义密码校验规则
const validatePassword = (rule, value, callback) => {
  if (value && (!/\d/.test(value) || !/[a-zA-Z]/.test(value))) {
    callback(new Error('密码必须包含字母和数字'))
  } else {
    callback()
  }
}

// 自定义确认密码校验规则
const validateConfirmPassword = (rule, value, callback) => {
  if (value !== registerForm.password) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' },
    { validator: validatePassword, trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ],
  // 种植户校验规则
  farmName: [
    { required: true, message: '请输入农场名称', trigger: 'blur' }
  ],
  farmAddress: [
    { required: true, message: '请输入农场地址', trigger: 'blur' }
  ],
  // 经销商校验规则
  companyName: [
    { required: true, message: '请输入公司名称', trigger: 'blur' }
  ],
  companyAddress: [
    { required: true, message: '请输入公司地址', trigger: 'blur' }
  ],
  businessLicense: [
    { required: true, message: '请上传营业执照', trigger: 'change' }
  ]
}

const register = () => {
  registerFormRef.value.validate(valid => {
    if (!valid) return
    
    // 构建注册数据
    const registerData = {
      username: registerForm.username,
      realName: registerForm.realName,
      phone: registerForm.phone,
      email: registerForm.email,
      role: registerForm.role,
      password: registerForm.password
    }
    
    // 根据角色添加对应的附加信息
    if (registerForm.role === 'FARMER') {
      registerData.farmInfo = {
        farmName: registerForm.farmName,
        farmAddress: registerForm.farmAddress,
        farmArea: registerForm.farmArea
      }
    } else if (registerForm.role === 'DEALER') {
      registerData.dealerInfo = {
        companyName: registerForm.companyName,
        companyAddress: registerForm.companyAddress,
        businessLicense: registerForm.businessLicense,
        businessLicenseUrl: registerForm.businessLicenseUrl
      }
    }
    const registerRequest=registerData
    // axios.post('api/users/register',registerData);
    axios.post('/api/users/register', registerRequest, {
      headers: {
        'Content-Type': 'application/json'  // 明确指定JSON格式
      }
    })

    console.log(registerRequest);
    // 在实际项目中，这里应该调用注册接口login_logs
    ElMessage.success('注册信息提交成功，请等待管理员审核')
    router.push('/login')
  })
}

const resetForm = () => {
  registerFormRef.value.resetFields()
}

// 处理营业执照上传成功
// const handleLicenseSuccess = (res, file) => {
//   // 实际项目中，这里应该从接口响应中获取文件的URL
//   registerForm.businessLicenseUrl = URL.createObjectURL(file.raw)
//   registerForm.businessLicense = file.name
// }
//
// // 上传前校验
// const beforeLicenseUpload = (file) => {
//   const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png'
//   const isLt2M = file.size / 1024 / 1024 < 2
//
//   if (!isJPGOrPNG) {
//     ElMessage.error('只能上传 JPG 或 PNG 格式的图片!')
//   }
//   if (!isLt2M) {
//     ElMessage.error('图片大小不能超过 2MB!')
//   }
//   return isJPGOrPNG && isLt2M
// }
</script>

<style scoped>
.register-container {
  padding: 20px 0;
  background-color: #f0f2f5;
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.register-box {
  width: 600px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 30px;
  margin-bottom: 20px;
}

.register-title {
  text-align: center;
  margin-bottom: 30px;
}

.register-title h3 {
  font-size: 22px;
  color: #303133;
  margin-bottom: 10px;
}

.register-title p {
  font-size: 16px;
  color: #606266;
}

.form-divider {
  font-size: 16px;
  color: #409EFF;
  margin: 20px 0;
  padding-bottom: 10px;
  border-bottom: 1px solid #EBEEF5;
}

.register-btn {
  margin-top: 20px;
  text-align: center;
}

.login-link {
  text-align: center;
  margin-top: 15px;
}

.login-link a {
  color: #409EFF;
  text-decoration: none;
}

.upload-area {
  width: 178px;
  height: 178px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.upload-area:hover {
  border-color: #409EFF;
}

.uploaded-image {
  width: 178px;
  height: 178px;
  display: block;
}

.upload-icon {
  font-size: 28px;
  color: #8c939d;
  margin-bottom: 8px;
}

.upload-text {
  font-size: 12px;
  color: #606266;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 7px;
}
</style> 